package com.example.jiradata.service;

import com.example.jiradata.dto.Iss;
import com.example.jiradata.dto.MembersResult;
import com.example.jiradata.jpa.JiraIssueTypeRepository;
import com.example.jiradata.jpa.JiraSecuritylevelRepository;
import com.example.jiradata.pojo.JiraIssueType;
import com.example.jiradata.pojo.JiraSecuritylevel;
import com.example.jiradata.utils.HttpClientUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class JiraSecuritylevelService {

    @Autowired
    private HttpClientUtils httpClientUtils;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    private JiraSecuritylevelRepository jiraSecuritylevelRepository;

    public void syncSecuritylevel() throws IOException {
        Set<Long> issueSecurityLevelIdSet = new HashSet<>();
        Iss iss = httpClientUtils.exchange("https://tngasia.atlassian.net/rest/api/2/issuesecurityschemes",new ParameterizedTypeReference<Iss>(){},null, HttpMethod.GET);
        for (Iss.IssueSecurityScheme issuesecurityscheme : iss.getIssueSecuritySchemes()) {
            MembersResult mr = httpClientUtils.exchange("https://tngasia.atlassian.net/rest/api/2/issuesecurityschemes/"+issuesecurityscheme.getId()+"/members?expand=all&startAt=0&maxResults=10000",new ParameterizedTypeReference<MembersResult>(){},null, HttpMethod.GET);
            for (MembersResult.Value value : mr.getValues()) {
                issueSecurityLevelIdSet.add(value.getIssueSecurityLevelId());
            }
        }

        for (Long aLong : issueSecurityLevelIdSet) {
            JiraSecuritylevel jiraSecuritylevel = httpClientUtils.exchange("https://tngasia.atlassian.net/rest/api/2/securitylevel/"+aLong,new ParameterizedTypeReference<JiraSecuritylevel>(){},null, HttpMethod.GET);
            jiraSecuritylevelRepository.save(jiraSecuritylevel);
        }

    }

}
